package com.quick.develop.flowable.framework.cmd;

import org.apache.commons.lang.StringUtils;
import com.quick.develop.flowable.utils.BpmTaskUtil;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cmd.NeedsActiveTaskCmd;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.HistoricTaskService;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.Objects;

/**
 * desc:
 *
 * @author junyuan.liu
 * @date 2023/10/26 10:02
 */
public class ClearTaskDescCmd extends NeedsActiveTaskCmd<Void> {

    protected String desc;

    public ClearTaskDescCmd(String taskId, String desc) {
        super(taskId);
        this.desc = desc;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        HistoricTaskService historicTaskService = CommandContextUtil.getHistoricTaskService(commandContext);
        TaskService taskService = CommandContextUtil.getTaskService(commandContext);
        HistoricTaskInstanceEntity historicTask = historicTaskService.getHistoricTask(taskId);
        String oldDesc = task.getDescription();
        if (StringUtils.isNotEmpty(oldDesc)) {
            String newDesc = BpmTaskUtil.clearDescription(oldDesc, desc);
            if (!Objects.equals(oldDesc, newDesc)) {
                task.setDescription(newDesc);
                historicTask.setDescription(newDesc);
                taskService.updateTask(task, false);
                historicTaskService.updateHistoricTask(historicTask, false);
            }
        }
        return null;
    }
}
